
package bcd;
public class linklist implements List{
	private node head;
	
	public linklist(){
		this.head=null;
	}
	
	
	public void clear() {
		this.head=null;
	}

	
	public boolean isEmpty() {
		return this.head==null;
	}

	
	public int length() {
		if(this.head==null){
			return 0;
		}
		int i=1;
		node pos=this.head.next;
		while(pos!=null){
			i++;
			pos=pos.next;
		}
		return i;
	}


	public Object get(int index) {
		if(index<1||index>this.length()){
			throw new ArrayIndexOutOfBoundsException("下标越界");
		}
		node pos=this.head;
		for(int i=1;i<index;i++){
			pos=pos.next;
		}
		return pos.data;
	}

	public int locate(Object o) {
		int len=this.length();
		node pos=this.head;
		for(int i=1;i<=len;i++){
			if(pos.data==o){
				return i;
			}
			pos=pos.next;
		}
		return -1;
	}

	public Object prior(Object o) {
              Object m=0;
             int n=0;
              node pos=this.head;
              if(head==null)
                  throw new ArrayIndexOutOfBoundsException("头结点是空.");
              if(pos.data==o)
                throw new ArrayIndexOutOfBoundsException("第一位的数没有前驱.");
              else {
                  pos=pos.next;
                  for(int i=2;i<=this.length();i++) {
                    if(pos.data==o){
                       m=get(i-1);
                     System.out.println("这个数的前继有;"+m);
                     n=-1;
                    }
                    pos=pos.next;
        
               }
              } 
              if(n==0)
                 throw new ArrayIndexOutOfBoundsException("该数不存在."); 
              return m;
	}

	
	public Object next(Object o) {
		node pos=this.head;
                Object m=0;
                for(int i=1;i<this.length();i++){
                    if(pos.data==o){
                        m=get(i+1);
                        System.out.println("这个数的后继有"+m);
                    }
                    pos=pos.next;
                    if(pos.next==null&&pos.data==o)
                         System.out.println("这个数的最后后继还有有null");
                }
               return m; 
	}

	
	public void insert(int index,Object o) {
	       node a=new node();
               a.data=o;
		if(index<0||index>this.length()){
			throw new ArrayIndexOutOfBoundsException("下标越界");
		}
		if(index==0){
			a.next=this.head;
			head=a;//进行过修改
		}else{
			node pos=this.head;
			for(int i=1;i<index;i++){
			pos=pos.next;
			}
			a.next=pos.next;
			pos.next=a;
		}
	}

	public Object delete(int index) {
		if(index<1||index>this.length()){
			throw new ArrayIndexOutOfBoundsException("下标越界");
		}
		if(index==1){
			Object a=this.head.data;
			node pos=this.head.next;
			this.head=pos;
			return a;
		}else{
			node pos=this.head;
			for(int i=1;i<index-1;i++){
				pos=pos.next;
			}
			Object a=pos.next.data;
			pos.next=pos.next.next;
			return a;
		}
	}

	public void traverse() {
		node pos=this.head;
		for(int i=1;i<=this.length();i++){
			System.out.print(pos.data+"  ");
			pos=pos.next;
		}
	}
	
}

    

